package com.ycl.bookstore.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.ycl.bookstore.DTO.UserDTO;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

import static com.ycl.bookstore.utils.RedisConstants.LOGIN_USER_TTL;

public class RefreshTokenInterceptor implements HandlerInterceptor {


    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("X-Token");
        //对刚登入的进行处理
        if(StrUtil.isBlank(token)){
            return true;
        }
        //通过token来查询用户
        String jsonUser= stringRedisTemplate.opsForValue().get(token);
        //通过token从redis中取出用户信息
        //如果没有信息  用户可能长时间没有对页面进行刷新
        if(jsonUser==null){
            //拦截
            return false;
        }
        UserDTO userDTO = JSONUtil.toBean(jsonUser, UserDTO.class);
        //将用户存到ThreadLocal中
        MyThreadLocal.saveUser(userDTO);
        //刷新token的有效期
        stringRedisTemplate.expire(token,LOGIN_USER_TTL, TimeUnit.MINUTES);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户
        MyThreadLocal.removeUser();
    }
}
